import {
  login,
  logout,
  getInfo
} from '@/api/login'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    loaded: false,
    resBaseUrl: '',
    banBtnList: [],
    loginForm: ''
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },

    SET_USER_INFO: (state, userInfo) => {
      console.log('userInfo', userInfo)
      state.name = userInfo.name
      state.sourceName = userInfo.sourceName
      state.tenantId = userInfo.tenantId
      state.deptNo = userInfo.deptNo
      state.deptId = userInfo.deptId
      state.username = userInfo.username
      state.avatar = userInfo.avatar
      state.resBaseUrl = userInfo.resBaseUrl
      state.banBtnList = userInfo.banBtnList
      state.loaded = true
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_LOGIN_FORM: (state, loginForm) => {
      state.loginForm = loginForm
    }
  },

  actions: {
    // 登录
    Login({
      commit
    }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo.username.trim(), userInfo.password).then(res => {
          const token = res.data.token
          setToken(token)
          commit('SET_TOKEN', token)
          commit('SET_LOGIN_FORM', userInfo)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response.data
          commit('SET_USER_INFO', data)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_LOGIN_FORM', '')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({
      commit
    }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_LOGIN_FORM', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
